Page({
  data: {
    phoneNumber: '',       // 手机号
    adminUserName: '',     // 控制端用户名
    hasControlPermission: false,  // 是否有控制端权限
    allCtrlPerms: []       // 控制端权限列表
  },

  onLoad(options) {
    // 从跳转页面获取手机号参数
    if (options.phoneNumber) {
      this.setData({ phoneNumber: options.phoneNumber });
      this.fetchPermissionData(options.phoneNumber);
    }
  },

  // 获取权限数据
  fetchPermissionData(phoneNumber) {
    wx.showLoading({ title: '加载中' });
    request({
      url: 'perms?phoneNumber=' + phoneNumber,
      method: 'GET'
    }).then(res => {
      if (res.code === 0) {
        this.setData({
          adminUserName: res.data.adminUserName || '',
          hasControlPermission: res.data.adminUserId !== 0,
          allCtrlPerms: res.data.allCtrlPerms || []
        });
      }
    }).finally(() => wx.hideLoading());
  },

  // 用户名输入
  onAdminNameInput(e) {
    this.setData({ adminUserName: e.detail.value });
  },

  // 权限项切换
  onCtrlPermChange(e) {
    const { index } = e.currentTarget.dataset;
    const { allCtrlPerms } = this.data;
    allCtrlPerms[index].selected = !allCtrlPerms[index].selected;
    this.setData({ allCtrlPerms });
  },

  // 保存
  onSave() {
    const { phoneNumber, adminUserName, allCtrlPerms } = this.data;
    const selectedPerms = allCtrlPerms.filter(item => item.selected).map(item => item.id);

    wx.showLoading({ title: '保存中' });
    request({
      url: 'perms/update',
      method: 'PUT',
      data: {
        phoneNumber,
        adminUserName,
        selectedPerms
      }
    }).then(() => {
      wx.showToast({ title: '保存成功', icon: 'success' });
      setTimeout(() => wx.navigateBack(), 1500);
    }).catch(() => {
      wx.showToast({ title: '保存失败', icon: 'none' });
    }).finally(() => wx.hideLoading());
  }
});